package vip.web3.common.utils;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by aut-hor on 2019/5/7.
 */
public class DesUtil {

    private static final byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };

    /**
     *
     * @param encryptString 要加密的内容
     * @param encryptKey 加密的key
     * @return
     * @throws Exception
     */
    public static String encryptDES(String encryptString, String encryptKey) throws Exception
    {
        IvParameterSpec zeroIv = new IvParameterSpec(encryptKey.getBytes());
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
        return Base64.encode(encryptedData);
    }

    /**
     *
     * @param decryptString 解密的内容
     * @param decryptKey 解密的key
     * @return
     * @throws Exception
     */
    public static String decryptDES(String decryptString, String decryptKey)
            throws Exception {
        byte[] byteMi = Base64.decode(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(decryptKey.getBytes());
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);
        return new String(decryptedData);
    }

    public static void main(String[] args) throws Exception {

        String plaintext = "mobile=17612842320&type=1";
        String ciphertext = encryptDES(plaintext, "20190627");
        System.out.println("明文：" + plaintext);
        System.out.println("密钥：" + "20190627");
        System.out.println("密文：" + ciphertext);

        String j0p9POuN = decryptDES("811ihA7ki55nLOtauT7P2q+Vwelm6cnp1+PXo2ZkK1o=", "20190627");
        System.out.println(j0p9POuN);
        System.out.println("timestamp=1618334038000");
        System.out.println("MD5：" + SignUtils.md5Password("timestamp=1618334038000"));
    }

}
